package com.ybwei.log.mdc.demo.interceptor;

import com.ybwei.log.mdc.demo.constant.MDCConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 拦截器-RestTemplate日志打印
 *
 * @author geoffrey
 * @version V1.0
 * @className LoggingRequestInterceptor
 * @date 2022/5/9
 **/
@Slf4j
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {


    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        //1、添加requestId
        String requestId = MDC.get(MDCConstant.REQUEST_ID);
        if (requestId != null) {
            request.getHeaders().add(MDCConstant.REQUEST_ID, requestId);
        }
        //2、打印请求参数
        traceRequest(request, body);
        //3、接口调用
        ClientHttpResponse response = execution.execute(request, body);
        //4、打印返回参数
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        log.info("请求开始,URI: {},Method: {},Headers: {}", request.getURI(), request.getMethod(), request.getHeaders());
        if (body.length < 1024) {
            log.info("Request body: {}", new String(body, "UTF-8"));
        }
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        log.info("请求结束,Status code  : {}", response.getStatusCode());
//        log.info("Status text  : {}", response.getStatusText());
//        log.info("Headers      : {}", response.getHeaders());
        if (inputStringBuilder.toString().length() < 1024) {
            log.info("Response body: {}", inputStringBuilder.toString());
        }
    }

}